package it.gestoreContratti.inputVerifiers;

import java.math.BigDecimal;

import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

public class NumericInputVerifier extends InputVerifier {
	
	private String field;
	private int length;	
	
	public NumericInputVerifier(String field, int len) {
		this.field = field;
		this.length = len;		
	}

	@Override
	public boolean verify(JComponent input) {
		JTextField textField = (JTextField) input;
		if(textField.getText().length() > length){
			JOptionPane.showMessageDialog(null, "Il campo "+field+" deve essere lungo al massimo "+length+" caratteri", "", JOptionPane.WARNING_MESSAGE);
			textField.setText("");
			textField.validate();
			return false;
		}
		else if(textField.getText().length() > 0){			
			try{
				
				if(textField.getText().contains(".")){
					String[] intDec = textField.getText().split("\\.");					
					if(intDec[1].length() > 2){
						JOptionPane.showMessageDialog(null, "Il campo "+field+" deve avere massimo due cifre decimali", "", JOptionPane.WARNING_MESSAGE);
						textField.setText("");
						textField.validate();
						return false;
					}
					new BigDecimal(textField.getText());					
					return true;
				}
				else{
					new BigDecimal(textField.getText());					
					return true;
				}				
			} catch (NumberFormatException e) {
				JOptionPane.showMessageDialog(null, "Il campo "+field+" deve essere un numero", "", JOptionPane.WARNING_MESSAGE);
				textField.setText("");
				textField.validate();
				return false;
			}			
		}else{
			return true;
		}
		
		
	}

}
